package com.ms.content.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ms.common.entiey.ALipayBean;
import com.ms.content.dao.MiaoshaActivityDao;
import com.ms.content.dao.OrderInfoDao;
import com.ms.content.entity.AlipayNotifyParam;
import com.ms.content.entity.MiaoshaActivityEntity;
import com.ms.content.entity.OrderInfoEntity;
import com.ms.content.service.OrderInfoService;
import com.ms.content.util.AliPayUtil;
import com.ms.content.util.AlipayConfig;
import com.ms.content.util.OssUtils;
import com.ms.content.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.ms.content.entity.GoodsEntity;
import com.ms.content.service.GoodsService;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 这个是商品表
 *
 * @author wc
 * @email sunlightcs@gmail.com
 * @date 2022-02-22 11:56:10
 */
@RestController
@RequestMapping("content/goods")
public class GoodsController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private OrderInfoDao orderInfoDao;



    @Autowired
    private MiaoshaActivityDao miaoshaActivityDao;

    //砍价 获取商品信息
    @RequestMapping("/kjgoods")
    public R kjgoods(@RequestParam("uuid") String uuid){
        R r = goodsService.showGoods(uuid);
        return r;
    }

    @RequestMapping("/pay")
    private R pay(@RequestParam String id) throws Exception {

        OrderInfoEntity orderInfoEntity = orderInfoService.getByIdbu(id);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderInfoEntity.getId().getBytes(), "UTF-8");
        System.out.println(orderInfoEntity.getId());
        //付款金额，必填
        String total_amount = new String(orderInfoEntity.getGoodsPrice().toString().getBytes(), "UTF-8");
        //订单名称，必填
        String subject = new String(orderInfoEntity.getGoodsName().getBytes(), "UTF-8");
        //商品描述，可空
        String body = new String("美国有苹果，中国有菠萝。菠萝手机，外置18亿高清摄像".getBytes(), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        System.out.println("商品订单号:"+out_trade_no);

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        System.out.println(alipayRequest);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return R.ok().put("connect",result);

    }

    /**
     * 回调地址
     */
    @RequestMapping("/huidiao")
    public void huidiao(@RequestBody AlipayNotifyParam alipayNotifyParam){
        System.out.println(alipayNotifyParam);
    }


    /**
     * 订单支付
     */
    @RequestMapping("/payorder")
    public R payorder(@RequestBody OrderInfoEntity orderInfoEntity) throws AlipayApiException {
        System.out.println(orderInfoEntity);
        OrderInfoEntity orderEntity = orderInfoService.getById(orderInfoEntity.getId());
        ALipayBean aLipayBean = new ALipayBean();
        aLipayBean.setOut_trade_no(orderEntity.getUserId());
        aLipayBean.setSubject(orderEntity.getGoodsName());
        aLipayBean.setTotal_amount(orderEntity.getGoodsPrice());
        aLipayBean.setBlody("牛逼666");
        System.out.println(aLipayBean);
        String connect = AliPayUtil.connect(aLipayBean);

        return R.ok().put("connenct",connect);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = goodsService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 根据id查询  商品数据信息
     */
    @RequestMapping("/byids/{id}")
    public R byids(@PathVariable("id") Integer id){
        return goodsService.seleById(id);
    }


    /**
     * 图片
     */
    @RequestMapping("/upload")
    public R  upload(MultipartFile file){
        return ossUtils.uploadFile(file);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		GoodsEntity goods = goodsService.getById(id);

        return R.ok().put("goods", goods);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody GoodsEntity goods){
		goodsService.save(goods);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody GoodsEntity goods){
		goodsService.updateById(goods);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		goodsService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    @RequestMapping("/deleteById/{id}")
    public R deleteById(@PathVariable("id")Integer id){
        goodsService.deleteById(id);
        return R.ok();
    }



    /**
     * 做页面缓存的list页面，防止同一时间访问量巨大到达数据库，如果缓存时间过长，数据及时性就不高。
     */




}
